﻿using System.Web.Mvc;
using Newtonsoft.Json;
using System;
using System.Globalization;

namespace CID.Web.Support
{
    public static class JSONExtensions
    {
        private class ShortDateTimeConverter : Newtonsoft.Json.Converters.DateTimeConverterBase
        {
            public override object ReadJson(JsonReader reader, System.Type objectType, object existingValue, JsonSerializer serializer)
            {
                throw new System.NotImplementedException();
            }

            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
                var dateTime = (DateTime) value;
                writer.WriteValue(dateTime.ToString(CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern));
            }
        }

        public static MvcHtmlString JSON<TModel>(this HtmlHelper<TModel> html, TModel model)
        {
            return MvcHtmlString.Create(JsonConvert.SerializeObject(model, new ShortDateTimeConverter()));
        }
    }
}